package com.nicy.dream.common;

import com.nicy.dream.utils.RandomUtil;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Random;

/**
 * @description:
 * @projectName:dream
 * @see:com.nicy.dream.common
 * @author:NicyYe
 * @createTime:2021/2/19 14:50
 * @version:1.0
 */
@Service
public class TokenServiceImpl implements TokenService{

    //前缀
    private final static String TOKEN_PREFIX = "dream_";
    private final static String TOKEN_NAME = "token";

    //注入redisService
    @Autowired
    private RedisService redisService;

    @Override
    public String createToken() {

        String str = RandomUtil.getUUID();
        StringBuffer token = new StringBuffer();

        try{
            token.append(TOKEN_PREFIX).append(str);
            redisService.setExt(token.toString(),token.toString(),10000L);
            boolean notEmpty = StringUtils.isNotEmpty(token.toString());
            if(notEmpty){
                return token.toString();
            }

        }catch (Exception e){
            e.printStackTrace();
        }


        return null;
    }

    /**
     * 检查token
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public boolean checkToken(HttpServletRequest request) throws Exception {
        String token = request.getHeader(TOKEN_NAME);
        if(StringUtils.isBlank(token)){
                //header中不存在token
            token = request.getParameter(TOKEN_NAME);
            if(StringUtils.isBlank(token)){
                //parameter中也不存在token
                throw new Exception("token不存在");
            }
        }

        if (!redisService.exists(token)) {
            throw new Exception("token已经存在");
        }

        boolean remove = redisService.remove(token);
        if (!remove) {
            throw new Exception("token已删除");
        }

        return true;
    }
}
